﻿using Furion;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using Ufangx.Xss;
using YFurion.DataFilters;
using YFurion.DataFilters.Extensions;
using YFurion.Extensions;
using YFurion.Localization;
using YFurion.Session;
using Yitter.IdGenerator;

namespace YFurion
{
    public class YFurionServiceComponent : IServiceComponent
    {
        public void Load(IServiceCollection services, ComponentContext componentContext)
        {
            ushort workerId = App.Configuration.Get<ushort>("IdGeneratorOptions:WorkerId");
            YitIdHelper.SetIdGenerator(new IdGeneratorOptions { WorkerId = workerId == 0 ? (ushort)1 : workerId });
            services.AddScoped<ILocalizationManager, LocalizationManager>()
                .AddScoped<IDataFilterOptions, DataFilterOptions>();
            bool isNative = App.Configuration.Get<bool>("IsNative");
            if (isNative)
            {
                services.AddSingleton<IYSession, YSession>();
                services.RegisterDataFilter(DataFilterConst.SoftDelete, true);
            }
            else
            {
                services.AddScoped<IYSession, YSession>();
            }
            string policyName = App.Configuration.Get<string>("XSSFilter:PolicyName");
            IWebHostEnvironment env = App.GetService<IWebHostEnvironment>();
            //添加策略和设置默认策略
            services.AddXssFilter(opt => opt.DefaultSchemeName = policyName.IsNullOrWhiteSpace() ? "DefaultPolicy" : policyName)
                .AddScheme<AntisamyPolicy>("antisamy", () => File.ReadAllTextAsync(Path.Combine(env.ContentRootPath, "resources/antisamy.xml")))
                .AddScheme<AntisamyPolicy>("anythinggoes", () => File.ReadAllTextAsync(Path.Combine(env.ContentRootPath, "resources/antisamy-anythinggoes.xml")))
                .AddScheme<AntisamyPolicy>("ebay", () => File.ReadAllTextAsync(Path.Combine(env.ContentRootPath, "resources/antisamy-ebay.xml")))
                .AddScheme<AntisamyPolicy>("myspace", () => File.ReadAllTextAsync(Path.Combine(env.ContentRootPath, "resources/antisamy-myspace.xml")))
                .AddScheme<AntisamyPolicy>("slashdot", () => File.ReadAllTextAsync(Path.Combine(env.ContentRootPath, "resources/antisamy-slashdot.xml")))
                .AddScheme<AntisamyPolicy>("test", () => File.ReadAllTextAsync(Path.Combine(env.ContentRootPath, "resources/antisamy-test.xml")))
                .AddScheme<JsonFilterPolicy>("DefaultPolicy", () => File.ReadAllTextAsync(Path.Combine(env.ContentRootPath, "resources/DefaultPolicy.json")));
        }
    }
}
